package com.disapand.strongarmy.controller

import cn.hutool.core.date.*
import cn.hutool.core.util.*
import com.disapand.strongarmy.vo.*
import org.springframework.beans.factory.annotation.*
import org.springframework.web.bind.annotation.*
import org.springframework.web.multipart.*
import java.io.*
import javax.servlet.http.*

/**
 *
 * @auth disapand
 * @date 2021/12/13 - 20:47 - 星期一
 *
 */
@RestController
@RequestMapping("/utils", name = "系统工具")
class UtilController {

    @Value(value = "\${file-save-path}")
    lateinit var fileSavePath: String

    @PostMapping("/upload-images", name = "上传文件")
    fun uploadImg(
        @RequestParam("file") file: MultipartFile,
        request: HttpServletRequest
    ): ResponseVO {
        val fileName = file.originalFilename!!
        val suffixName = fileName.substring(fileName.lastIndexOf("."))
        val newFileName = IdUtil.simpleUUID() + suffixName
        val directory = "images/" +  DateUtil.format(DateUtil.date(), "yyyy/MM/dd") + "/"
        val dir = File(fileSavePath + directory)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        val newFile = File(fileSavePath + directory + newFileName)
        file.transferTo(newFile)
        val url = request.scheme + "://" + request.serverName + ":" + request.serverPort + "/" + directory + newFileName
        return ResponseVO.ofSuccess(url)
    }
}